import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import Home from '../views/Home.vue'
import {list} from '../../sa.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    redirect:'/home', //重定向到welcome
    meta: {
      title:'主页',
      requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
    },
    children:[
      { 
        path: '/home', 
        component: Home,
        meta: {
          title:'欢迎',
          requireAuth: true,
        }
      },
      // { 
      //   path: '/userlist', 
      //   component: () => import('../components/Users/UserList.vue'),
      //   meta: {
      //     title:'用户列表',
      //     requireAuth: true
      //   }
      // },
      // { 
      //   path: '/userinfo', 
      //   component: () => import('../components/Users/UserInfo.vue'),
      //   meta: {
      //     title:'用户详情',
      //     requireAuth: true, 
      //   } 
      // }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component:() => import('../views/Login.vue')
  },
  {
    path: "*",
    name: "NotFound",
    component: () => import("../views/NotFound.vue"),
  },
]
//获取动态路由

const dynamicRoutes = () => {
  console.log(list);
  list.forEach(item => {
    if(item.children.length){
      item.children.forEach(itemc => {
        routes[1].children.push(
          { 
            path: "/" + itemc.path, 
            component: () => import(`../components/Users/${itemc.component}.vue`),
            meta: {
              title:itemc.authName,
              requireAuth: true, 
            } 
          })
      })
    }
  })
}
dynamicRoutes()

console.log(routes,'路由');
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作 next('/login')强制跳转login
router.beforeEach((to, from, next) => {
  //判断是否需要权限访问
  if(to.meta.requireAuth){
    if(localStorage.getItem('token')){//判断是否有token
      next()
    }else{
      next({
        path:'/login',
        query:{
          redirect:to.fullPath
        }
      })
    }
  }else{
    next()
  }
})
export default router

